//
// Created by LiuYou on 2021/11/25.
//

#ifndef HTTP_SERVER_SEM_HPP
#define HTTP_SERVER_SEM_HPP


#include <semaphore.h>
#include <cstdio>
#include <cerrno>
#include <cstring>
#include <stdexcept>


/**
 * @brief 和 Mutex类一样, 为线程同步机制封装类, 本类封装了posix信号量。
 *
 * @note 没有考虑异常。
 * @see Mutex类, Cond类。
 * @since 0.1
 *
 * @author ly
 */
class Sem final {
public:
    explicit Sem(unsigned int semInitialValue = 0) {
        int ret = sem_init( &semaphore, 0, semInitialValue );
        if (ret < 0) {
            fprintf( stderr, "sem_init(): %s.\n", strerror(errno));
            throw std::runtime_error( std::string( "sem_init(): " ) + strerror(errno) + "." );
        }
    }

    ~Sem() {
        sem_destroy( &semaphore );
    }

    bool wait() {
        int ret = sem_wait( &semaphore );
        if (ret < 0) {
            perror( "sem_wait()" );
//            throw std::runtime_error( std::string( "sem_wait(): " ) + strerror(errno) + "." );
            return false;
        }
        return true;
    }

    bool post() {
        int ret = sem_post( &semaphore );
        if (ret < 0) {
            perror( "sem_post()" );
//            throw std::runtime_error( std::string( "sem_post(): " ) + strerror(errno) + "." );
            return false;
        }
        return true;
    }

private:
    sem_t semaphore{};

};


#endif //HTTP_SERVER_SEM_HPP
